package processmanagement

import (
	"fmt"
	"math/rand"
	"time"
)

// 定义进程结构体
type Process struct {
	Pid      int
	Priority int
	Size     int
	Status   int
	Data     interface{}
}

// 定义变量
var (
	ProcessList = [10]Process{}
	Memory      = make(map[int]Process)
	Pending     = make(map[int]Process)
	Flag        = 0
)

// 创建随机的不在内存中的进程
func Create() {
	rand.Seed(time.Now().UnixMilli())
	for i := 0; i < len(ProcessList); i++ {
		ProcessList[i].Pid = rand.Intn(100)
		ProcessList[i].Priority = rand.Intn(100)
		ProcessList[i].Size = rand.Intn(100)
		ProcessList[i].Status = 0
		ProcessList[i].Data = rand.Intn(100)
	}
	fmt.Printf("当前所有进程：")
	for i := 0; i < len(ProcessList); i++ {
		fmt.Printf("PID:%v\t", ProcessList[i].Pid)
	}
}

// 根据Pid运行某个进程
func RunProces(pid int) {
	if pid == 0 {
		return
	}
	for i := 0; i < len(ProcessList); i++ {
		if ProcessList[i].Pid == pid {
			ProcessList[i].Status = 1
			// 添加到内存中
			Memory[pid] = ProcessList[i]
			Flag = 1
			fmt.Printf("PID为：%v 的进程已运行\n", pid)
		}
	}
	if Flag == 0 {
		fmt.Println("当前没有运行进程")
		return
	}
}

// 根据PID换出某个进程
func SwapOut(pid int) {
	if len(Memory) == 0 {
		fmt.Println("当前没有运行进程")
		return
	}
	for i := 0; i < len(ProcessList); i++ {
		if ProcessList[i].Pid == pid {
			if ProcessList[i].Status == 1 {
				ProcessList[i].Status = 2
				// 添加到挂起列表中
				Pending[pid] = ProcessList[i]
				fmt.Printf("PID为：%v 的进程已成功换出\n", pid)
			} else if ProcessList[i].Status == 0 {
				fmt.Printf("PID为：%v 的进程不存在\n", pid)
			} else {
				fmt.Printf("PID为：%v 的进程已被挂起\n", pid)
			}
			Flag = 1
			break
		}
	}
	if Flag == 0 {
		fmt.Println("要换出的进程不存在")
		return
	}
}

// 根据PID杀死某个进程
func KillProcess(pid int) {
	if len(Memory) == 0 {
		fmt.Println("当前没有运行进程")
		return
	}
	for i := 0; i < len(ProcessList); i++ {
		if ProcessList[i].Pid == pid {
			if ProcessList[i].Status == 1 {
				ProcessList[i].Status = 0
				delete(Memory, pid)
				fmt.Printf("PID为：%v 的进程已成功杀死\n", pid)
			} else if ProcessList[i].Status == 0 {
				fmt.Printf("PID为：%v 的进程不存在\n", pid)
			} else {
				fmt.Printf("PID为：%v 的进程已被挂起\n", pid)
			}
			Flag = 1
			break
		}
	}
	if Flag == 0 {
		fmt.Println("要换出的进程不存在")
		return
	}
}

// 根据PID唤醒某个进程
func WakeUp(pid int) {
	if len(Memory) == 0 {
		fmt.Println("当前没有运行进程")
		return
	}
	for i := 0; i < len(ProcessList); i++ {
		if ProcessList[i].Pid == pid {
			if ProcessList[i].Status == 2 {
				ProcessList[i].Status = 1
				delete(Pending, pid)
				fmt.Printf("PID为：%v 的进程已成功唤醒\n", pid)
			} else if ProcessList[i].Status == 0 {
				fmt.Printf("PID为：%v 的进程不存在\n", pid)
			} else {
				fmt.Printf("PID为：%v 的进程是运行状态\n", pid)
			}
			Flag = 1
			break
		}
	}
	if Flag == 0 {
		fmt.Println("要换出的进程不存在")
		return
	}
}
